import { ref } from 'vue'
import { ElMessageBox } from 'element-plus'

const currentPicked = ref({
    latlng: {},
})

export function openTencentMapPickPop(tencentMapApiKey: string) {
    const IFRAME_HTML = `<iframe class="q" width="100%" height="500" frameborder="0"
              src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${tencentMapApiKey}&referer=myapp"></iframe>`
    ElMessageBox({
        title: '选择地址',
        message: IFRAME_HTML,
        customClass: 'location-picker-box',
        dangerouslyUseHTMLString: true,
        closeOnPressEscape: false,
    })
        .then(() => {
            window.removeEventListener('message', handleMapPickedMessage, false)
            window.parent.postMessage(
                {
                    type: 'tencent-map-data',
                    data: JSON.stringify(currentPicked.value),
                },
                '*'
            )
        })
        .catch((e) => {
            if (e != 'cancel') {
                console.log(e)
            }
            window.removeEventListener('message', handleMapPickedMessage, false)
        })
    window.addEventListener('message', handleMapPickedMessage, false)
}
function handleMapPickedMessage(event: { data: any }) {
    const loc = event.data
    if (loc && loc.module != 'locationPicker') return
    currentPicked.value = loc
}
